#define _CRT_SECURE_NO_WARNINGS 1
#include "SList.h"
void Print(SLTNode* phead)
{
	SLTNode* cur = phead;
	while (cur)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}
SLTNode* BuyListNode(SLTDataType x)//创建节点
{
	SLTNode* newnode = malloc(sizeof(SLTNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit (- 1);
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}
//要使参数在函数中改变要传参数的地址
//要使指针在函数中改变要传指针的地址
//必须要有简引用的过程才能赋值
void SLTPushBack(SLTNode** phead, SLTDataType x)//二级指针接收
{
	SLTNode* newnode = BuyListNode(x);
	if (*phead == NULL)
	{
		//改变结构体的指针，要用结构体指针的指针（二级指针）
		*phead = newnode;
	}
	else
	{
		SLTNode* tail = *phead;
		while (tail->next != NULL)
			{
				tail = tail->next;
			}
		//改变的结构体，用结构体的指针
		tail->next = newnode;
	}

}

//*pphead == plist
void SLTPushFront(SLTNode** pphead, SLTDataType x)
{
	SLTNode* newnode = BuyListNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}

void SLTPopBack(SLTNode** pphead)
{
	//1，空
	assert(*pphead);
	// 2，一个结点
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	//3，
	else
	{
		//第一种
		//SLTNode* tail = *pphead;
		//SLTNode* tailPrev = NULL;//记录tail前一个结点
		//while (tail->next)
		//{
		//	tailPrev = tail;
		//	tail = tail->next;
		//}
		//tailPrev->next = NULL;
		//free(tail);
		
		//第二种
		SLTNode* tail = *pphead;
		while (tail->next->next)//找到倒数第二个结点
		{
			tail = tail->next;
		}
		free(tail->next);
		tail->next = NULL;
	}
}

void SLTPopFront(SLTNode** pphead)
{
	//1，空
	assert(*pphead);
	//2,非空
	SLTNode* tail = *pphead;
	*pphead = tail->next;//头结点指向下一个
	free(tail);

}
SLTNode* SListFind(SLTNode* plist, SLTDataType x)
{
	//有问题？
	//for (SLTNode* cur = plist; cur != NULL; cur=cur->data)
	//{
	//	if (cur->data == x)
	//	{
	//		return cur;
	//	}
	//}
	//return NULL;
	SLTNode* cur = plist;
	while (cur)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	assert(pos);
	if (*pphead == pos)
	{
		SLTPushFront(pphead, x);
	}
	else
	{
		SLTNode* prev = *pphead;//存储pos前一个结点
		while (prev->next != pos)//比较两个结点的地址，不能比较值
		{
			prev = prev->next;
		}
		SLTNode *newnode= BuyListNode(x);
		prev->next = newnode;
		newnode->next = pos;
	}
}

void SLTInsertAfter(SLTNode* pos, SLTDataType x)
{
	assert(pos);

	SLTNode* newnode = BuySListNode(x);
	pos->next = newnode;
	newnode->next = pos->next;
}

// 删除pos位置
void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	assert(pphead);
	assert(pos);

	if (pos == *pphead)
	{
		SLTPopFront(pphead);
	}
	else
	{
		SLTNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}

		prev->next = pos->next;
		free(pos);
		//pos = NULL;
	}
}

// 删除pos的后一个位置
void SLTEraseAfter(SLTNode* pos)
{
	assert(pos);

	// 检查pos是否是尾节点
	assert(pos->next);

	SLTNode* posNext = pos->next;

	pos->next = posNext->next;

	free(posNext);
	posNext = NULL;
}